﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Happy.ExtentionMethods;

namespace Happy.Domain
{
    /// <summary>
    /// 泛型版本的聚合根基类。
    /// </summary>
    public abstract class AggregateRoot<TId> : Entity<TId>, IAggregateRoot<TId>
    {
        /// <summary>
        /// 构造方法。
        /// </summary>
        protected AggregateRoot() { }

        /// <summary>
        /// 构造方法。
        /// </summary>
        protected AggregateRoot(TId id)
            : base(id)
        {
        }

        /// <summary>
        /// 乐观锁字段。
        /// </summary>
        public byte[] OptimisticKey { get; protected set; }

        /// <summary>
        /// 判断是否出现乐观并发，如果出现就抛出异常。
        /// </summary>
        public void CheckConcurrent(byte[] optimisticKey)
        {
            optimisticKey.MustNotEmpty("optimisticKey");

            if (string.Join(string.Empty, optimisticKey) != string.Join(string.Empty, this.OptimisticKey))
            {
                throw new OptimisticConcurrencyException();
            }
        }
    }
}
